package com.aoip.telemetry.telemetry.receive.message.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageCodec;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;

import java.util.List;

/**
 * @author chenbai
 * @version 1.0
 * @Description TODO
 * @date 2022/7/6 20:51
 */
@ChannelHandler.Sharable
@Slf4j
public class DatagramPacketMessageCodecSharable extends MessageToMessageCodec<DatagramPacket, String> {

    @Override
    protected void encode(ChannelHandlerContext ctx, String msg, List<Object> out) {

    }

    @Override
    protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) {
        ByteBuf buf = packet.copy().content();
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String originalMessage = new String(req);
        log.error("报文：{},localAddress:{}", originalMessage, ctx.channel().localAddress());

        Channel channel = ctx.channel();
        ByteBuf heapBuffer = channel.alloc().heapBuffer();
        heapBuffer.writeBytes(originalMessage.getBytes());

        DatagramPacket sendPacket = new DatagramPacket(heapBuffer, packet.sender());
        ctx.writeAndFlush(originalMessage);
        out.add(originalMessage);

    }
}
